<?php

/**
 * Class CallbackAction
 * @modif lilei<LL_strive@163.com> 2017-04-21
 *
 * [1] - 逻辑修改
 * 之前是在微信公众号授权之后, 把公众号名称写到customer_user里, 而且是通过cid唯一指定. 现在由于cid下多用户, 这样该肯定不科学, 这是改逻辑原因之一; 另外, 在访问控制模块中加入了对用户的编辑, 可以修改其fullName, 所以这里不需要修改
 * @modif lilei<LL_strive@163.com> 2017-07-26
 */
class CallbackAction extends Action
{

    public function _initialize()
    {
        /**
         * LLyeap_wx_customer修改
         */
        $this->customer_db = D("Customer");
        $this->ind_media_info_db = D('ind_media_info');
        $this->customer_user_db = D("CustomerUser");
        $this->customer_weixin_profile_db = D('CustomerWeixinProfile');
        $this->gg_user_db = D('GgUser');
        // $this->wechatPlatform = new WechatThirdPlatform();
    }

    public function get_component_access_token()
    {
        echo WechatThirdPlatform::get_component_access_token();
    }

    public function Open()
    {

        $result = WechatThirdPlatform::decrypt_msg();
        log::write('result_start' . json_encode($result));
        if ($result['code'] == 1) {
            $result = WechatThirdPlatform::deal_biz($result['msg'], $result);
            switch ($result['info_type']) {
                case 'authorized':
                    //全网发布逻辑
                    if ($result['authorizer_appid'] == 'wx570bc396a51b8ff8') {
                        $this->deal_authorized($result);
                    }
                    break;
                case 'unauthorized':
                    $this->deal_unauthorized($result);
                    break;
                case 'updateauthorized':
                    $this->deal_authorized($result);
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 第三方授权后回调函数
     */
    public function redirect()
    {
        /**
         * {
         * "output": "json",
         * "cid": "3",
         * "third_platform_appid": "wxe3e7b9570b4bec69",
         * "normal": "/nmp/index.html?router=joymap/wechatPlatform/normal",
         * "error": "/nmp/index.html?router=joymap/wechatPlatform/repeat",
         * "auth_code": "queryauthcode@@@mcZM_382JeaimUIytZGM09GgcXJozG7cqIv6FQjjVbyNte6anPsNdYN7wbZmpM8dggWAWO7OhCs08WMLkgT7AQ",
         * "expires_in": "3600",
         * "_URL_": [
         * "Callback",
         * "redirect"
         * ]
         * }
         */
        $result = $_GET;
        $auth_code = $result['auth_code'];
        $cid = $result['cid'];
        $mediaId = $result['mediaId'];  // 在授权回调中, 新怎mediaId, 用来具体到某个自媒体账号
        $normal = $result['normal'];
        $error = $result['error'];
        $isGaogao = $result['isGaogao'];
        if (!$normal) {
            $normal = '/nmp/index.html#/wechatPlatform/normal';
        }
        if (!$error) {
            $error = '/nmp/index.html#/wechatPlatform/repeat';
        }
        if ($isGaogao == 1) {
            $normal = C('AUTH_BACK_SERVER_HOST') . '/gaogao/index.html#' . $normal;
            $error = C('AUTH_BACK_SERVER_HOST') . '/gaogao/index.html#' . $error;
        }

        log::write('result:' . json_encode($result));
        if ($auth_code && $cid > 0) {

            if ($mediaId == 0) {    // $mediaId = 0, 则使用默认公众号信息
                $map = ['cid' => $cid, 'isDefault' => 1];
            } else {    // 为特定自媒体账号授权的回调, 选择指定自媒体
                $map = ['id' => $mediaId, 'cid' => $cid];
            }
            $component_appid = $this->ind_media_info_db->where($map)->getField('third_platform_appid');

            /***** LLyeap_delete *****/
//            $map = array();
//            $map['id'] = $cid;
//            $component_appid = $this->customer_db->where($map)->getField('third_platform_appid');
            /*****  *****/

            $authorization_info = WechatThirdPlatform::get_authorizer_info($component_appid, $auth_code);
            $authorizer_appid = $authorization_info->authorizer_appid;

            // 去重判断
            $repeat['imi.appid'] = $authorizer_appid;
            if ($mediaId == 0) {    // 以前的授权去重规则, 如果在此账号以外的cid下进行了授权, 那么这个账号便不能再次授权
                $repeat['imi.cid'] = array('neq', $cid);
            } else {    // 微梦想升级授权, 不通过cid来进行过滤, 而是通过mediaId, 这样, 这个账号在同一个cid下进行了授权也是不可以的
                $repeat['imi.id'] = array('neq', $mediaId);
                if ($isGaogao == 1) {   // 这个是稿稿平台内进行授权, 在同一个cid下, 授权不可以重复
                    $repeat['imi.cid'] = array('eq', $cid);
                } else {    // 如果不是稿稿平台内进行授权, 要求在稿稿所有用户的cid外, 不重复
                    // 先从wx_gg_user表里查询出选稿人的cid(select_cid), 然后在这个数组里添加上稿稿本身的cid, 在授权时, 过滤掉这些cid
                    $ggCids = M()->table('wx_gg_user')->where(['select_cid' => array('exp', 'is not null')])->getField('select_cid', TRUE);
                    array_push($ggCids, GG_CUSTOMERID);
                    $repeat['imi.cid'] = array('not in', $ggCids);
                }
            }
            $repeat['cwp.grantStatus'] = 1;
            $repeat['imi.deleted'] = 0;
            $has_count = $this->ind_media_info_db
                ->alias('imi')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile cwp ON cwp.mediaId = imi.id')
                ->where($repeat)
                ->count();

            /***** LLyeap_delete *****/
//            $repeat = array();
//            $repeat['a.appid'] = $authorizer_appid;
//            $repeat['a.id'] = array('neq', $cid);
//            $repeat['b.grantStatus'] = 1;
//            $has_count = $this->customer_db->alias('a')
//                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//                ->where($repeat)
//                ->count();
            /*****  *****/

            if ($has_count > 0) {
                header("Location:" . $error . '?isError=1');
                return;
            } else {
                $authorizer_info_base = WechatThirdPlatform::get_authorization_base_info($component_appid, $authorizer_appid);
                $result['authorization_info'] = $authorization_info;
                $result['authorizer_info_base'] = $authorizer_info_base;
                // 处理未认证账号
                // 授权方认证类型，-1代表未认证，0代表微信认证，1代表新浪微博认证，2代表腾讯微博认证，3代表已资质认证通过但还未通过名称认证，4代表已资质认证通过、还未通过名称认证，但通过了新浪微博认证，5代表已资质认证通过、还未通过名称认证，但通过了腾讯微博认证
                // 这里需要做个renturn
//                if ($authorizer_info_base->authorizer_info->verify_type_info->id == -1) {
//                    header("Location:" . $error . '?isError=1');
//                    return;
//                }

                $qrcode_url = $authorizer_info_base->authorizer_info->qrcode_url;

                if ($qrcode_url) {
                    $oss_qrcode_url = download_file($qrcode_url);
                }
                $result['qrcode_url'] = $oss_qrcode_url;
                $result['service_open_status']['location_report'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'location_report')->option_value;
                $result['service_open_status']['voice_recognize'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'voice_recognize')->option_value;
                $result['service_open_status']['customer_service'] = WechatThirdPlatform::get_authorizer_set($component_appid, $authorizer_appid, 'customer_service')->option_value;
                $this->deal_authorized($result);

                //稿稿平台绑定自媒体用户积分增加
                if ($isGaogao == 1) {
                    R("GgGrade/dealBuyerMediaGrade", array($mediaId));
                    $this->GgSelfmedia($cid, $mediaId);
                }
                header("Location:" . $normal);
            }
        } else {
            header("Location:" . $error . '?isError=1');
            return;
        }
    }

    public function GgSelfmedia($cid, $mediaId)
    {
        Session::switchCustomer(0);
        $customer_user = M('customer_user');
        $wx_gg_user = M('gg_user');
        $cuid = $wx_gg_user->where(['select_cid' => $cid])->getField('cuid');

        $mediaCount = R("GgContribute/getIndMediaList", array($name = null, $start = 0, $limit = 1000, $cuid));
        if ($mediaCount == 1) {
            //写手升级为买手时进行原有的信息完善积分同步
            R("GgGrade/syncWriterMessageGrade", array($mediaId));

            $customer_user->where(['customerId' => $cid, 'agent' => 'business'])->setField('status', 'open');
            $wx_gg_user = M('gg_user');
            $selectinfo['role'] = 'selfmedia';
            $selectinfo['selfmediaTime'] = date('Y-m-d H:i:s', time());
            $wx_gg_user->where(['select_cid' => $cid])->save($selectinfo);
            $message = "亲爱的用户，您已成功激活选稿方身份。平台将会你提供在线征稿、自媒体运营等相关服务。";
            $wxmessage = "亲爱的用户，您已成功激活选稿方身份。平台将会你提供在线征稿、自媒体运营等相关服务。";
            PlatMessageAction::pushMessage('系统消息', $message, array($cuid), 3, 0, 'systemMessage', '系统消息', 1, 1, $callType = 0, $sendType = 0, $wxmessage, 3, wallet);
        }
    }

    /**
     * 头条号第三方授权后回调函数
     */
    public function redirectToutiao()
    {
        $result = $_GET;
        $code = $result['code'];
        $state = $result['state'];
        $state = explode('_', $state);
        $mediaId = $state[1];
        $normal = $state[3];
        $error = $state[5];
        //判断获得code是否成功
        if ($code) {
            //数据库模型
            Session::switchCustomer(0);
            $media = M('ind_media_info');
            $toutiao = M('customer_toutiao_profile');
            $third = M('third_platform');
            $mediaInfo = $media->field("cid")->where("id=$mediaId")->find();
            $thirdInfo = $third->field("appid,appsecret")->where("type=3")->find();
            $customerId = $mediaInfo['cid'];
            Session::switchCustomer($customerId);


            $client_key = $thirdInfo['appid'];
            $client_secret = $thirdInfo['appsecret'];
            $result = ToutiaoApi::getThirdToutiaoAccessToken($code, $client_key, $client_secret);
            //判断获得accesstoken是否成功
            if ($result['ret'] == 0) {
                //判断数据库中是否已经存在这个头条号的信息
                $mediaInfo = ToutiaoApi::getThirdToutiaoInfo($client_key, $result['data']['access_token']);
                if ($mediaInfo['message'] !== 'error') {
                    //头条号具体信息表新增数据
                    $result_toutiao = $toutiao->field('id')->where("mediaId=$mediaId")->find();
                    if ($result_toutiao) {
                        $uid = $result['data']['uid'];
                        $where['tou.uid'] = $uid;
                        $where['tou.mediaId'] = array("NEQ", $mediaId);
                        $where['me.deleted'] = 0;
                        $find_result = $toutiao
                            ->alias('tou')
                            ->where($where)
                            ->join('left join wx_ind_media_info me ON me.id = tou.mediaId')
                            ->field('me.id')
                            ->find();
                        if ($find_result) {
                            Output::instance()->object([
                                'code' => 1,
                                'msg' => '该头条号已经在此平台授权, 无需重新授权',
                                'data' => []
                            ]);
                            exit;
                        }
                        //在媒体账号表里进行accesstoken信息保存
                        $data['accessToken'] = $result['data']['access_token'];
                        $data['expired'] = date('Y-m-d H:i:s', $result['data']['expires_in'] - 60);
                        $media->where("id=$mediaId")->save($data);
                        $toutiaoInfo['screen_name'] = $result['data']['screen_name'];
                        $toutiaoInfo['open_id'] = $result['data']['open_id'];
                        $toutiaoInfo['uid_type'] = $result['data']['uid_type'];
                        $toutiaoInfo['uid'] = $result['data']['uid'];
                        $toutiaoInfo['grantTime'] = date('Y-m-d H:i:s');
                        $toutiaoInfo['grantStatus'] = 1;
                        $toutiaoInfo['media_id'] = $mediaInfo['media_id'];
                        $toutiaoInfo['description'] = $mediaInfo['description'];
                        $toutiaoInfo['extra'] = $mediaInfo['extra'];
                        $toutiaoInfo['avatar_url'] = $mediaInfo['avatar_url'];
                        $toutiaoInfo['media_name'] = $mediaInfo['media_name'];
                        $toutiaoInfo['user_verified'] = $mediaInfo['user_verified'];
                        $save_result = $toutiao->where("id=" . $result_toutiao['id'])->save($toutiaoInfo);
                        $toutiao_sql = $toutiao->getLastSql();
                        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $toutiao_sql, '更新头条号的相关信息'));
                        if ($save_result !== false) {
                            header("Location:" . $normal);
                        } else {
                            header("Location:" . $error);
                        }
                    } else {
                        $uid = $result['data']['uid'];
                        $where['tou.uid'] = $uid;
                        $where['me.deleted'] = 0;
                        $find_result = $toutiao
                            ->alias('tou')
                            ->where($where)
                            ->join('left join wx_ind_media_info me ON me.id = tou.mediaId')
                            ->field('me.id')
                            ->find();
                        if ($find_result) {
                            Output::instance()->object([
                                'code' => 1,
                                'msg' => '该头条号已经在此平台授权, 无需重新授权',
                                'data' => []
                            ]);
                            exit;
                        }
                        //在媒体账号表里进行accesstoken信息保存
                        $data['accessToken'] = $result['data']['access_token'];
                        $data['expired'] = date('Y-m-d H:i:s', $result['data']['expires_in'] - 60);
                        $media->where("id=$mediaId")->save($data);
                        $toutiao->create();
                        $toutiao->cid = $customerId;
                        $toutiao->mediaId = $mediaId;
                        $toutiao->screen_name = $result['data']['screen_name'];
                        $toutiao->open_id = $result['data']['open_id'];
                        $toutiao->uid_type = $result['data']['uid_type'];
                        $toutiao->uid = $result['data']['uid'];
                        $toutiao->grantTime = date('Y-m-d H:i:s');
                        $toutiao->grantStatus = 1;
                        $toutiao->media_id = $mediaInfo['media_id'];
                        $toutiao->description = $mediaInfo['description'];
                        $toutiao->extra = $mediaInfo['extra'];
                        $toutiao->avatar_url = $mediaInfo['avatar_url'];
                        $toutiao->media_name = $mediaInfo['media_name'];
                        $toutiao->user_verified = $mediaInfo['user_verified'];
                        $newId = $toutiao->add();
                        $toutiao_sql = $toutiao->getLastSql();
                        R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_add, $toutiao_sql, '添加头条号的相关信息'));
                        if (!$newId) {
                            header("Location:" . $error);
                        } else {
                            header("Location:" . $normal);
                        }
                    }

                } else {
                    header("Location:" . $error);
                }
            } else {
                header("Location:" . $error);
            }


        } else {
            header("Location:" . $error);
        }

    }

    /**
     * 微博号第三方授权后回调函数
     */
    public function redirectWeibo()
    {
        $code = $_GET['code'];
        //通过state区分是哪个mediaId和回调状态
        $state = $_GET['state'];
        $state = explode('_', $state);
        $mediaId = $state[1];
        $normal = $state[3];
        $error = $state[5];

        //**数据库模型*/
        Session::switchCustomer(0);
        $media = M('ind_media_info');
        $weibo = M('customer_weibo_profile');
        $third = M('third_platform');
        $mediaInfo = $media->field("cid,third_platform_appid")->where("id=$mediaId")->find();
        $thirdInfo = $third->field("appid,appsecret")->where("appid=" . $mediaInfo['third_platform_appid'])->find();
        $customerId = $mediaInfo['cid'];
        Session::switchCustomer($customerId);

        $data = WeiboApi::getThirdWeiboAccesstoken($code, $thirdInfo['appid'], $thirdInfo['appsecret']);
        if ($data['error']) {
            header("Location:" . $error);
        } else {
            $weibo_result = $weibo->field()->where("mediaId=$mediaId")->find();
            //获得微博用户的基本信息
            $result = WeiboApi::getThirdWeiboInfo($data['access_token'], $data['uid']);
            if ($result['error']) {
                header("Location:" . $error);
            } else {
                //进行结果转换
                if ($result['allow_all_act_msg']) {
                    $result['allow_all_act_msg'] = 1;
                } else {
                    $result['allow_all_act_msg'] = 0;
                }
                if ($result['geo_enabled']) {

                    $result['geo_enabled'] = 1;
                } else {
                    $result['geo_enabled'] = 0;
                }
                if ($result['verified']) {
                    $result['verified'] = 1;
                } else {
                    $result['verified'] = 0;
                }
                if ($result['allow_all_comment']) {
                    $result['allow_all_comment'] = 1;
                } else {
                    $result['allow_all_comment'] = 0;
                }
                if ($result['follow_me']) {
                    $result['follow_me'] = 1;
                } else {
                    $result['follow_me'] = 0;
                }
                if ($result['online_status']) {
                    $result['online_status'] = 1;
                } else {
                    $result['online_status'] = 0;
                }


                //之前存在就保存，之前不存在就add到数据库
                if ($weibo_result) {
                    $uid = $data['uid'];
                    $where['wei.uid'] = $uid;
                    $where['wei.mediaId'] = array("NEQ", $mediaId);
                    $where['me.deleted'] = 0;
                    $find_result = $weibo
                        ->alias('wei')
                        ->where($where)
                        ->join('left join wx_ind_media_info me ON me.id = wei.mediaId')
                        ->field('me.id')
                        ->find();
                    if ($find_result) {
                        Output::instance()->object([
                            'code' => 1,
                            'msg' => '该微博号已经在此平台授权, 无需重新授权',
                            'data' => []
                        ]);
                        exit;
                    }
                    $data_media['accessToken'] = $data['access_token'];
                    $data_media['expired'] = date('Y-m-d H:i:s', time() + $data['expires_in'] - 60);
                    $media->where("id=$mediaId")->save($data_media);
                    $data['idstr'] = $result['idstr'];
                    $data['screen_name'] = $result['screen_name'];
                    $data['name'] = $result['name'];
                    $data['province'] = $result['province'];
                    $data['city'] = $result['city'];
                    $data['location'] = $result['location'];
                    $data['description'] = $result['description'];
                    $data['url'] = $result['url'];
                    $data['profile_image_url'] = $result['profile_image_url'];
                    $data['profile_url'] = $result['profile_url'];
                    $data['domain'] = $result['domain'];
                    $data['weihao'] = $result['weihao'];
                    $data['gender'] = $result['gender'];
                    $data['followers_count'] = $result['followers_count'];
                    $data['friends_count'] = $result['friends_count'];
                    $data['statuses_count'] = $result['statuses_count'];
                    $data['favourites_count'] = $result['favourites_count'];
                    $data['created_at'] = $result['created_at'];
                    $data['following'] = $result['following'];
                    $data['allow_all_act_msg'] = $result['allow_all_act_msg'];
                    $data['gen_enabled'] = $result['gen_enabled'];
                    $data['verified'] = $result['verified'];
                    $data['verified_type'] = $result['verified_type'];
                    $data['remark'] = $result['remark'];
                    $data['status'] = $result['status'];
                    $data['allow_all_comment'] = $result['allow_all_comment'];
                    $data['avatar_large'] = $result['avatar_large'];
                    $data['avatar_hd'] = $result['avatar_hd'];
                    $data['verified_reason'] = $result['verified_reason'];
                    $data['follow_me'] = $result['follow_me'];
                    $data['online_status'] = $result['online_status'];
                    $data['bi_followers_count'] = $result['bi_followers_count'];
                    $data['lang'] = $result['lang'];
                    $save_result = $weibo->where("id=" . $weibo_result['id'])->save($data);
                    $weibo_sql = $weibo->getLastSql();
                    R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_update, $weibo_sql, '更新微博号的相关信息'));
                    if ($save_result !== false) {
                        header("Location:" . $normal);
                    } else {
                        header("Location:" . $error);
                    }
                } else {
                    $uid = $data['uid'];
                    $where['wei.uid'] = $uid;
                    $where['me.deleted'] = 0;
                    $find_result = $weibo
                        ->alias('wei')
                        ->where($where)
                        ->join('left join wx_ind_media_info me ON me.id = wei.mediaId')
                        ->field('me.id')
                        ->find();
                    if ($find_result) {
                        Output::instance()->object([
                            'code' => 1,
                            'msg' => '该微博号已经在此平台授权, 无需重新授权',
                            'data' => []
                        ]);
                        exit;
                    }
                    $data_media['accessToken'] = $data['access_token'];
                    $data_media['expired'] = date('Y-m-d H:i:s', time() + $data['expires_in'] - 60);
                    $media->where("id=$mediaId")->save($data_media);
                    $weibo->create();
                    $weibo->cid = $customerId;
                    $weibo->mediaId = $mediaId;
                    $weibo->uid = $data['uid'];
                    $weibo->grantTime = date('Y-m-d H:i:s');
                    $weibo->grantStatus = 1;
                    $weibo->idstr = $result['idstr'];
                    $weibo->screen_name = $result['screen_name'];
                    $weibo->name = $result['name'];
                    $weibo->province = $result['province'];
                    $weibo->city = $result['city'];
                    $weibo->location = $result['location'];
                    $weibo->description = $result['description'];
                    $weibo->url = $result['url'];
                    $weibo->profile_image_url = $result['profile_image_url'];
                    $weibo->profile_url = $result['profile_url'];
                    $weibo->domain = $result['domain'];
                    $weibo->weihao = $result['weihao'];
                    $weibo->gender = $result['gender'];
                    $weibo->followers_count = $result['followers_count'];
                    $weibo->friends_count = $result['friends_count'];
                    $weibo->statuses_count = $result['statuses_count'];
                    $weibo->favourites_count = $result['favourites_count'];
                    $weibo->created_at = $result['created_at'];
                    $weibo->following = $result['following'];
                    $weibo->allow_all_act_msg = $result['allow_all_act_msg'];
                    $weibo->gen_enabled = $result['gen_enabled'];
                    $weibo->verified = $result['verified'];
                    $weibo->verified_type = $result['verified_type'];
                    $weibo->remark = $result['remark'];
                    $weibo->status = $result['status'];
                    $weibo->allow_all_comment = $result['allow_all_comment'];
                    $weibo->avatar_large = $result['avatar_large'];
                    $weibo->avatar_hd = $result['avatar_hd'];
                    $weibo->verified_reason = $result['verified_reason'];
                    $weibo->follow_me = $result['follow_me'];
                    $weibo->online_status = $result['online_status'];
                    $weibo->bi_followers_count = $result['bi_followers_count'];
                    $weibo->lang = $result['lang'];
                    $addId = $weibo->add();
                    $weibo_sql = $weibo->getLastSql();
                    R('Log/add', array('indmediaManagement', '139', '自媒体管理', op_add, $weibo_sql, '增加微博号的相关信息'));
                    if ($addId) {
                        header("Location:" . $normal);
                    } else {
                        header("Location:" . $error);
                    }
                }

            }

        }

    }

    public function wechat_oauth()
    {
        // echo LOCAL_PIC_PATH;
        // exit;
        $qrcode_url = 'http://mmbiz.qpic.cn/mmbiz/oFtxYw8LmCloicQjvCE3ROuxgdp6ERQKNHMosGBd2PF27DuMOJDLMicGVPlVA9ykstDtK3iboBiaMIjMwpbOFUqdNQ/0';
        $img_url = download_file($qrcode_url);
        echo 'img_url=' . $img_url;
        echo 'OLDSERVER_HOST=' . C('OLDSERVER_HOST') . '<br/>';
        echo 'SERVER_NAME=' . C('SERVER_HOST') . '<br/>';
        echo 'RESOURCEURL=' . C('SERVER_HOST') . '<br/>';

        echo 'RESOURCEURL=' . C('ACT_DETAIL_SHARE_TITLE') . '<br/>';
        $url = WechatThirdPlatform::get_oauth_url();
        echo $url;
        exit;
    }

    /**
     * 授权方法，参数result：授权信息
     * @param $result
     */
    public function deal_authorized($result)
    {
        \Log::write('lilei_3_' . 'enter_deal_authorized' . json_encode($result));
        $authorization_info = $result['authorization_info'];
        $authorizer_info_base = $result['authorizer_info_base'];
        $authorizer_info = $authorizer_info_base->authorizer_info;
        $authorization_info_base = $authorizer_info_base->authorization_info;
        $cid = $result['cid'];
        $mediaId = $result['mediaId'];
        $isGaogao = $result['isGaogao'];
        $third_platform_appid = $result['third_platform_appid'];

        if ($authorization_info && $authorizer_info) {
            $authorizer_appid = $authorization_info->authorizer_appid;
            $authorizer_access_token = $authorization_info->authorizer_access_token;
            $authorizer_refresh_token = $authorization_info->authorizer_refresh_token;

            $map = $save_data = array();
            if ($cid && $cid > 0) {
                if ($mediaId && $mediaId > 0) { // 指定了特定的自媒体
                    $map['imi.id'] = $mediaId;
                    $map['imi.cid'] = $cid;
                } else {    // 使用这个cid下默认自媒体
                    $map['imi.cid'] = $cid;
                    $map['imi.isDefault'] = 1;
                }
            } else {
                $map['imi.appid'] = $authorizer_appid;
            }

            $save_data['appid'] = $authorizer_appid;
            $save_data['accessToken'] = $authorizer_access_token;
            $save_data['accessExpiration'] = time() + 7000;
            $save_data['mode'] = 1;
            $save_data['refreshToken'] = $authorizer_refresh_token;

            $this->ind_media_info_db->startTrans();

            $customer_info = $this->ind_media_info_db
                ->alias(imi)
                ->field('imi.id as mediaId, imi.cid as cid, imi.third_platform_appid, cwp.id as customer_weixin_profile_id')
                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile cwp ON cwp.mediaId = imi.id')
                ->where($map)
                ->find();

            /***** LLyeap_delete *****/
//            $this->customer_db->startTrans();
//
//            $customer_info = $this->customer_db->alias('a')
//                ->field('a.id as cid,a.third_platform_appid,b.id as customer_weixin_profile_id')
//                ->join('left join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//                ->where($map)
//                ->find();
            /*****  *****/

            log::write('customer_info:' . json_encode($customer_info));
            if (!$customer_info['third_platform_appid']) {
                $third_platform_appid = WechatThirdPlatform::check_component_appid($third_platform_appid);

                $save_data['third_platform_appid'] = $third_platform_appid;
            }
            $customer_result = $this->ind_media_info_db->alias('imi')->where($map)->save($save_data);

            /***** LLyeap_delete *****/
//            $customer_result = $this->customer_db->alias('a')->where($map)->save($save_data);
            /*****  *****/

            if ($customer_info) {
                $func_info_array = array();
                $func_info = $authorization_info_base->func_info;
                foreach ($func_info as $key => $value) {
                    $func_info_array[$key] = $value->funcscope_category->id;
                }
                $func_info_str = implode(',', $func_info_array);
                $customer_weixin_profile_id = $customer_info['customer_weixin_profile_id'];
                $customer_weixin_profile_data = array();
                $customer_weixin_profile_data['cid'] = $customer_info['cid'];
                $customer_weixin_profile_data['mediaId'] = $customer_info['mediaId'];

                // > 修改注释[1]
//                $this->customer_user_db->where('customerId=' . $cid)->setField('fullName', $authorizer_info->nick_name);
                $customer_weixin_profile_data['nick_name'] = $authorizer_info->nick_name;

                $customer_weixin_profile_data['head_img'] = $authorizer_info->head_img;
                $customer_weixin_profile_data['service_type_info'] = $authorizer_info->service_type_info->id;
                $customer_weixin_profile_data['verify_type_info'] = $authorizer_info->verify_type_info->id;
                $customer_weixin_profile_data['user_name'] = $authorizer_info->user_name;
                $customer_weixin_profile_data['principal_name'] = $authorizer_info->principal_name;
                $business_info = $authorizer_info->business_info;
                $business_info = json_encode($business_info);
                Log::write('business_info:' . $business_info . 'length:' . strlen($business_info));
                $customer_weixin_profile_data['business_info'] = $business_info;

                $customer_weixin_profile_data['alias'] = $authorizer_info->alias;
                $qrcode_url = $authorizer_info->qrcode_url;
                if ($result['qrcode_url']) {
                    $qrcode_url = $result['qrcode_url'];
                }
                $customer_weixin_profile_data['qrcode_url'] = $qrcode_url;
                $customer_weixin_profile_data['alias'] = $authorizer_info->alias;
                $customer_weixin_profile_data['func_info'] = $func_info_str;
                $customer_weixin_profile_data['grantTime'] = date('Y-m-d H:i:s');
                $customer_weixin_profile_data['grantStatus'] = 1;
                $customer_weixin_profile_data['service_open_status'] = json_encode($result['service_open_status']);
                if ($customer_weixin_profile_id > 0 && $isGaogao != 1) {
                    $customer_weixin_profile_map = array();
                    $customer_weixin_profile_map['id'] = $customer_weixin_profile_id;
                    $customer_weixin_profile_result = $this->customer_weixin_profile_db->where($customer_weixin_profile_map)->save($customer_weixin_profile_data);
                } else {
                    $customer_weixin_profile_result = $this->customer_weixin_profile_db->add($customer_weixin_profile_data);
                }

            } else {
            }
            Log::write('customer_sql:' . $this->ind_media_info_db->_sql());
            Log::write('customer_weixin_profile_sql:' . $this->customer_weixin_profile_db->_sql());
            if ($customer_result && $customer_weixin_profile_result) {
                // 稿稿平台前台过来的授权, 修改授权者身份为自媒体人
                if ($isGaogao) {
                    $where_GgUser = ['select_cid' => $cid];
                    $data_GgUser = ['role' => 'selfmedia'];
                    $result_GgUser = $this->gg_user_db->where($where_GgUser)->save($data_GgUser);
                    if (!is_numeric($result_GgUser)) {
                        \Log::write('授权回调-修改自媒体人身份错误: sql=' . $this->gg_user_db->getLastSql());
                    }
                }
                $this->ind_media_info_db->commit();
            } else {
                $this->ind_media_info_db->rollback();
            }
        }


    }

    /**
     * 取消授权代码
     *
     * @param $result
     */
    public function deal_unauthorized($result)
    {
        $map['imi.appid'] = $result['authorizer_appid'];
        $map['cwp.grantStatus'] = 1;
        $customer_info = $this->ind_media_info_db->alias('imi')
            ->field('imi.id, imi.cid')
            ->join('inner join ' . C('DB_PREFIX') . 'customer_weixin_profile cwp ON cwp.mediaId = imi.id')
            ->where($map)
            ->find();

        /***** LLyeap_delete *****/
//        $map = array();
//        $map['a.appid'] = $result['authorizer_appid'];
//        $map['b.grantStatus'] = 1;
//        // $map['a.mode'] = 1;
//        $customer_info = $this->customer_db->alias('a')
//            ->field('a.id')
//            ->join('inner join ' . C('DB_PREFIX') . 'customer_weixin_profile b on a.id = b.cid')
//            ->where($map)->find();
        /*****  *****/

        if ($customer_info) {

            $update_grantStatus_result = $this->customer_weixin_profile_db
                ->where(['cid' => $customer_info['cid'], 'mediaId' => $customer_info['id']])
                ->setField('grantStatus', 0);

            $imi_map['appid'] = $result['authorizer_appid'];
            $this->ind_media_info_db->where($imi_map)->setField('mode', 0);

            /***** LLyeap_delete *****/
//            $update_grantStatus_result = $this->customer_weixin_profile_db
//                ->where('cid=' . $customer_info['id'])
//                ->setField('grantStatus', 0);
//                $customer_map = array();
//                $customer_map['appid'] = $result['authorizer_appid'];
//            $this->customer_db->where($customer_map)->setField('mode', 0);
            /***** LLyeap_delete *****/

            Log::write('update_grantStatus_sql:' . $this->ind_media_info_db->_sql());
            log::write('grantStatus_sql:' . $this->customer_weixin_profile_db->_sql());
        }

    }

    /**
     * 发起微信授权
     * 由于稿稿平台未升级为第三方平台, 所以在授权时, 稿稿的域名不可用, 这里需要稿稿跳到微梦想平台下进行在此跳转授权
     * @param $url  微信授权url地址
     */
    public function spons_auth($url, $mediaId, $cid, $third_platform_appid)
    {
        // TODO: 注意容错处理
        // 第一个先拼上$mediaId, 授权成功后, 跳转详情页面
        $url .= $mediaId . '&cid=' . $cid . '&mediaId=' . $mediaId . '&third_platform_appid=' . $third_platform_appid;
        $oauth_url = WechatThirdPlatform::get_oauth_url($third_platform_appid, $url, $mediaId);

        echo '<script>window.location.href="' . $oauth_url . '"</script>';
    }


    /**
     * 入口函数，调用路径
     * http://localhost/callback/index.json/signature/sign/timestamp/20110302113322/nonce/3/echostr/abc
     * http://localhost/callback.json/?signature=sign&timestamp=20110302113322&nonce=3&echostr=abc
     */
    public function index($signature = '', $timestamp = '', $nonce = 0, $echostr = '')
    {
        switch ($_SERVER['REQUEST_METHOD']) {
            case 'GET':
                $this->access($signature, $timestamp, $nonce, $echostr, '');
                break;
            case 'POST': {  // get post data, May be due to the different environments
                if ($_GET['appid']) {
                    log::write('index:');
                    log::write("liupeng_post:" . json_encode($_POST));
                    log::write("liupeng_post:" . json_encode($_GET));
                    $customerInfo = $this->currentCustomer();
                    $msg = WechatThirdPlatform::decrypt_msg($customerInfo->third_platform_appid);
                    if ($msg['code'] == 1) {
                        $postStr = $msg['msg'];
                    } else {
                        Log::write("消息解密失败  " . json_encode($msg));
                    }
                } else {
                    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
                }

                // extract post data
                if (!empty($postStr)) {
                    $message = Message::getInstance($postStr);
log::write('liIndex:'.json_encode($message));
                    $appid = $_GET['appid'];
                    if ($appid == "wx570bc396a51b8ff8") {    // 微信测试第三方平台全网发布用的公众号
//                        Session::switchCustomer($customerInfo->id);
                        Session::switchCustomer($customerInfo->cid);
                        $this->deal_test_publish($appid, $message);
                    } else {
log::write('liuIndex1111');

                        if (!($message->msgType[0] == message_type_event && $message->event == message_type_event_scan)) {
                            $Redis = new RedisAPI();
                            if (isset($message->msgId) && ($message->msgId != 0)) {   // 如果存在msgId
                                $key = PRE_RESPONSE_MSG_ . $message->msgId;
                            } else {    // 如果不存在msgId - 事件类消息
                                $key = PRE_RESPONSE_MSG_ . $message->fromUserName . $message->createTime;
                            }
                            $isExist = $Redis->get($key);
log::write($key);
log::write('liIndex:'.$isExist);
                            if ($isExist == 1) {    // 如果存在
log::write('lpIndex1111');
                                echo "";
                                return;
                            }
                            // 不存在, 则将此次消息互动, 放入redis队列
                            $redis_result = $Redis->set($key, 1, 15);   // 设置15s过期
                        }

                        /** 为了区分媒体平台, 这里将mediaId加入到message中 */
                        $message->indMediaId = $customerInfo->id;
                        $this->responseMsg($message);
                    }
                } else {
                    echo "";
                    exit;
                }
            }
                break;
        }
    }

    /**
     * 全网发布代码
     *
     * @param $appid
     * @param $message
     */
    public function deal_test_publish($appid, $message)
    {
        $openid = $_GET['openid'];
        log::write('test_appid' . $appid);
        log::write('推送测试信息get' . json_encode($_GET));
        log::write('测试信息' . json_encode($message));
        log::write('msgType:' . $message->msgType);
        switch ($message->msgType) {
            case message_type_event:
                $content = $message->event;
                $content = $content . 'from_callback';
                log::write('进入了此方法');
                $result = WeixinApi::sendServiceMsg($openid, 'text', $content);
                log::write('type_event_result:' . json_encode($result));
                break;
            case message_type_text:
                $content = $message->content;
                if ($content == 'TESTCOMPONENT_MSG_TYPE_TEXT') {
                    $content = $content . '_callback';
                } else {
                    $content = str_replace('QUERY_AUTH_CODE:', '', $content);
                    $content = $content . '_from_api';
                }
                WeixinApi::sendServiceMsg($openid, 'text', $content);
                break;
            default:
                break;
        }
    }

    /**
     * 获取当前用户
     * 微信URL：<host>/api.php/callback/id/xxx
     * @return null|object
     */
    private function currentCustomer()
    {
        $uuid = $_GET['id'];
        $appid = $_GET['appid'];
        if (!isset($uuid) && !isset($appid)) {
            echo "invalid url";
            return NULL;
        }

        /**
         * 这地方customer是为了或得wx_customer信息
         * ** 这里需要全局uuid - 需要为每个账号给一个uuid
         * LLyeap_wx_customer修改
         */
        /***** LLyeap_delete *****/
        $CustomerModule = D('customer');
        /*****  *****/

        $IndMediaInfo_Model = D('ind_media_info');

        if ($appid) {
            $where['imi.appid'] = array('eq', $appid);
            $where['imi.mode'] = array('eq', 1);
            $where['cwp.grantStatus'] = array('eq', 1);
            $where['imi.deleted'] = array('eq', 0);
            $customer = $IndMediaInfo_Model
                ->alias("imi")
                ->join("inner join `wx_customer_weixin_profile` cwp ON cwp.mediaId = imi.id")
                ->field("imi.*")
                ->where($where)
                ->find();

            /***** LLyeap_delete *****/
//            $where['a.appid'] = array("eq", $appid);
//            $where['a.mode'] = array("eq", 1);
//            $where['b.grantStatus'] = array("eq", 1);
//            $customer = $CustomerModule->alias("a")
//                ->join("inner join `wx_customer_weixin_profile` b on a.id=b.cid")
//                ->field("a.*")
//                ->where($where)->find();
            /*****  *****/

        } else if ($uuid) {

            $where['uuid'] = $uuid;
            $customer = $IndMediaInfo_Model->where($where)->find();

            /***** LLyeap_delete *****/
//            $customer = $CustomerModule->where($where)->find();
            /*****  *****/
        }
        if (!isset($customer)) {
            echo "invalid customer";
            return NULL;
        }
        return (object)$customer;
    }

    // TODO: 这地方$mediaId没有用
    private function verifyCustomer($cid, $mediaId)
    {
        $CUModel = D('customer_user');
        $where['customerId'] = $cid;
        $where['agent'] = array(array('eq', 'agent'), array('eq', 'business'), 'or');
        $where['status'] = 'open';
        $customerUser = $CUModel->where($where)->find();
        return $customerUser;
    }

    /* 
     * 处理网络接入
     */
    private function access($signature, $timestamp, $nonce, $echostr, $customerId)
    {
        Log::write('Enter function access');

        $customer = $this->currentCustomer();
        if (!isset($customer)) {
            echo "invalid customer";
            return;
        }

        $tmpArr = array($customer->token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            echo $echostr;
            exit;
        } else {
            echo "signature failed";
        }
    }


    /**
     * 处理微信公众消息查询推送
     *
     * @$message    微信公众号消息查询的消息
     * @modify lilei<LL_strive@163.com> 2017-04-24
     */
    private function responseMsg($message)
    {
        Log::write('Enter function responseMsg');
        \Log::write('llyeap_message_' . json_encode($message));
        /**
         * {
         *  "content": "lilei_2",
         *  "fromUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
         *  "toUserName": "gh_e86a027dc440",
         *  "createTime": "2017-07-18 10:25:24",
         *  "msgType": {
         *      "0": "text"
         *  },
         *  "msgId": 6443931522725400000
         *  "mediaId": 3
         * }
         */
        // 确定当前客户
        $customer = $this->currentCustomer();
        if (!isset($customer)) {
            $replyMsg = $message->reply(message_type_text);
            $replyMsg->content = "";
            $replyMsg->funcFlag = 1;//加星标
            echo $replyMsg->to_xml_string();
            return;
        } else {
            $customerUser = $this->verifyCustomer($customer->cid, $customer->id);
            if (!isset($customerUser)) {
                return;
            }
        }

        // 切换客户
//        Session::switchCustomer($customer->id);
        Session::switchCustomer($customer->cid);

        // 保存message
        $this->saveMessage($message, $customer);
        if (!isset($replyMsg)) {
            // 处理用户状态
            $replyMsg = $this->handleUserStatus($message);
            if ($replyMsg && $replyMsg->ispost) {
                $this->postCallModule($replyMsg);
            }
        }
        // 关键字模块处理消息后会修改消息内容，所以使用临时变量
        // $msgOriginal = new stdClass();
        // foreach ($message as $k => $v) {
        //    $msgOriginal->$k = $v;
        // }
        if ($message->content) {
            $message->content = str_replace("'", "&apos;", $message->content);
        }

        if (!isset($replyMsg) || !$replyMsg) {    // 各类型消息的缺省处理

            switch ($message->msgType[0]) {     // 第0个元素才是准确的类型, e.g.{0:image}
                case message_type_text:
                    // TODO: 这里调用下层方法原本返回的都是对象
                    // 这里改为数组返回
                    // 在switch之后, 需要用循环来做对应处理
                    // $replyMsg = $this->handleText($message);
                    $arr_replyMsg = $this->handleText($message);
                    /**
                     * [
                     * {
                     * "articles": [
                     * {
                     * "title": "ll",
                     * "description": {},
                     * "picUrl": "http://mmbiz.qpic.cn/mmbiz_jpg/oFtxYw8LmCmDlBp9KsbROlrmLSPUfk5YAmGqXE8EXpBdb48iaVoDE53upw3Z0qqcnzFyDBzrne42iakpMkAKy9Zw/0",
                     * "content": {},
                     * "url": {}
                     * }
                     * ],
                     * "fromUserName": "gh_e86a027dc440",
                     * "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                     * "createTime": 1500438257,
                     * "msgType": "news",
                     * "funcFlag": 0
                     * },
                     * {
                     * "content": "ll6-7",
                     * "fromUserName": "gh_e86a027dc440",
                     * "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                     * "createTime": 1500438257,
                     * "msgType": "text",
                     * "funcFlag": 0
                     * },
                     * {
                     * "content": "",
                     * "fromUserName": "gh_e86a027dc440",
                     * "toUserName": "o7pYBuA5V87miNm2TtcWj7rDNso8",
                     * "createTime": 1500438257,
                     * "msgType": "image",
                     * "funcFlag": 0,
                     * "media_id": "19apvY0Op9dSdSQg0qNkDN7cVkym_1o-Rytu4UFcUVQ"
                     * }
                     * ]
                     */
                    break;
                case message_type_event: {
                    switch ($message->event) {
                        case message_type_event_subscribe:
                            $arr_replyMsg = $this->handleSubscribe($message, $customer);
                            break;
                        case message_type_event_unsubscribe:
                            $arr_replyMsg = $this->handleUnsubscribe($message);
                            break;
                        case message_type_event_click:
                            $arr_replyMsg = $this->handleClick($message);
                            break;
                        case message_type_event_view:
                            $arr_replyMsg = $this->handleView($message);
                            // 不返回消息
                            $arr_replyMsg = (isset($arr_replyMsg) && !empty($arr_replyMsg)) ? $arr_replyMsg : [];
                            break;
                        case message_type_event_scan:
                            $replyMsg = $this->handleScan($message);
                            $arr_replyMsg = [$replyMsg];    // 20170725 - 没细入
                            break;
                        case message_type_event_location:
                            // $replyMsg = $this->handleLocation($message); // 这里小白龙原来是没有的, 所以注释掉
                            break;
                        case message_type_event_mass:    // 事件推送群发结果
                            $arr_replyMsg = $this->handleMass($message);
                            // 不返回消息
                            $arr_replyMsg = (isset($arr_replyMsg) && !empty($arr_replyMsg)) ? $arr_replyMsg : [];
                            break;
                        default:    // 记录日志
                            Log::write('Unknown event type:' . $message->event);
                    }
                    break;
                }
                case message_type_image:
                    $arr_replyMsg = $this->handleImage($message);   // 类似于关注
                    break;
                case message_type_location:
                    $arr_replyMsg = $this->handleLocation($message);    // 类似于关注
                    break;
                case message_type_link:
                    $arr_replyMsg = $this->handleLink($message);    // 类似于关注
                    break;
                case message_type_voice:
                    $arr_replyMsg = $this->handleVoice($message);   // 类似于关注
                    break;
                case message_type_video:
                    $arr_replyMsg = $this->handleVideo($message);   // 类似于关注
                    break;
                case message_type_service:  // 客服
                    $replyMsg = $this->handleService($message);
                    // (非最佳处理)客服消息触发, 如果不在客服时间, 则返回一条"不在客服时间", 如果在客服时间, 则转入人工客服处理
                    $arr_replyMsg = [$replyMsg];
                    break;
                default:
                    // 记录日志
                    Log::write('Unknown message type:' . $message->msgType);
            }
        }


        // 默认回复
        if (empty($arr_replyMsg) && !($replyMsg && $replyMsg->isModule)) {
            if (strcasecmp($message->msgType, message_type_event) != 0 && strcasecmp($message->event, message_type_location) != 0) {
                $arr_replyMsg = $this->handleDefault($message);
//                 if (!empty($replyMsg)) {
//                 	$replyMsg->funcFlag = 1;//加星标
//                 }
            }
        }

        foreach ($arr_replyMsg as $k => $replyMsg) {
            CustomService::customSend($customer->cid, $customer->id, $replyMsg);

            // 设置回复信息则保存回复消息
            $this->saveReplyMessage($replyMsg, $message->msgId, $customer->cid);
        }

        // 本来这里是需要对上文排重进行取消的, 这里用了redis, 设置过期时间, 故无需加此操作

        /**
         * 20170719 - 旧的逻辑
         * 在此之前, 消息互动这块使用微信被动消息回复来实现
         * 在此之后, 消息互动使用微信的客服消息来实现, 就是上面那块
         */

        /**
         * // 默认回复
         * if (empty($replyMsg)) {
         * if (strcasecmp($message->msgType, message_type_event) != 0 && strcasecmp($message->event, message_type_location) != 0) {
         * $replyMsg = $this->handleDefault($message);
         * //                 if (!empty($replyMsg)) {
         * //                    $replyMsg->funcFlag = 1;//加星标
         * //                 }
         * }
         * }
         *
         * if ($replyMsg && $replyMsg->isModule) {
         * echo "";
         * return "";
         * }
         * if (empty($replyMsg) || $message->msgType[0] == 'image') {  // 张鑫需求: 公众号收到图片消息时,不响应公众号推送
         * echo "";
         * $issetReply = false;
         * } else {
         * if ($_GET['appid']) {
         * \Log::write('lilei_3' . WechatThirdPlatform::encrypt_msg($customer->third_platform_appid, $replyMsg->to_xml_string()));
         * echo WechatThirdPlatform::encrypt_msg($customer->third_platform_appid, $replyMsg->to_xml_string());
         * } else {
         * \Log::write('lilei_4' . $replyMsg->to_xml_string());
         * echo $replyMsg->to_xml_string();
         * }
         * $issetReply = true;
         * }
         * if ($issetReply) {  // 设置回复信息则保存回复消息
         * $this->saveReplyMessage($replyMsg, $message->msgId, $customer->id);
         * } else {
         * // 非关键字消息则调用判断是否需要推送
         * //            if ($message->msgType == 'text') {
         * //                $isPushNotKw = Module::callModule(module_handle_pushMsg, NULL, 'isPushNotKeyword', NULL);
         * //                if ($isPushNotKw) {
         * //                    $params = new stdClass();
         * //                    $params->type = module_handle_text;
         * //                    $params->title = '收到用户发到【%s】公众帐号的信息:\n';
         * //                    $params->msg = $message->content;
         * //                    Module::callModule(module_handle_pushMsg, NULL, 'pushMsgToBind', $params);
         * //                }
         * //            }
         * }
         */
    }


    /**
     * 异步调用
     *
     * @param $regMsg
     * @return bool
     */
    private function postCallModule($regMsg)
    {
        $cid = Session::$user['customerId'];
        $url = C("SERVER_HOST") . "call.html?customerId=" . $cid;
        $msg['module'] = $regMsg->module;
        $msg['method'] = $regMsg->method;
        $msg['params'] = urlencode(json_encode($regMsg->params));
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 设置curl允许执行的最长秒数为5
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return true;
    }

    /**
     * 保存回复数据到数据库
     *
     * @param $msg
     * @param $msgId
     * @param $cid
     */
    private function saveReplyMessage($msg, $msgId, $cid)
    {
        Log::write('Enter function saveReplyMessage');
        $Message = D("Message");
        $Message->create();
        $Message->fromUserName = (String)$msg->fromUserName;
        $Message->toUserName = (String)$msg->toUserName;
        $Message->msgType = (String)$msg->msgType;
        $Message->msgId = $msgId;
        $Message->customerId = $cid;
        $Message->createTime = date('Y-m-d H:i:s', (String)$msg->createTime);
        $Message->msgMark = message_type_reply;
        switch ($msg->msgType) {
            case message_type_text:
                $Message->content = trim($msg->content);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_music:
//     			$Message->title = trim($msg->title);
//     			$Message->description = trim($msg->description);
//     			$Message->url = trim($msg->musicUrl);
//     			$Message->reserve2 = trim($msg->hqMusicUrl);
                break;
            case message_type_news:
                //$array = $msg->articles;
                $Message->content = WeixinApi::newsToHtml($msg->articles);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add News Message Error:' . $Message->getError());
                }
                break;
            default: // 记录日志
                break;
        }
    }

    /**
     * 保存数据到数据库
     *
     * @param $msg
     * @param $customer
     */
    private function saveMessage($msg, $customer)
    {
//        $cid = $customer->id;
        $cid = $customer->cid;
        Log::write('Enter function saveMessage');
        //判断积分表是否存在
        $CustomerModule = new Model();
        //$pointsModuleSql = 'SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = "weixin" AND table_name = "wx_'.$cid.'_module_set_points"';
//     	$pointsResult = $CustomerModule->query($pointsModuleSql);
//     	$SetPoints = null;
//     	if($pointsResult[0][count] >0 ){
// 	    	$SetPoints = D("module_set_points");
//     	}
        $Message = D("Message");
        $Message->create();
        $Message->fromUserName = (String)$msg->fromUserName;
        $Message->toUserName = (String)$msg->toUserName;
        $Message->msgType = (String)$msg->msgType;
        $Message->msgId = $msg->msgId;
        $Message->customerId = $cid;
        $Message->msgMark = message_type_receive;
        $Message->createTime = $msg->createTime;
        switch ($msg->msgType) {
            case message_type_text:
                $Message->content = trim($msg->content);
                break;
            case message_type_event: {
                switch ($msg->event) {
                    case message_type_event_subscribe:
                    case message_type_event_unsubscribe:
                    case message_type_event_click:
                    case message_type_event_view:
                        $Message->eventKey = $msg->eventKey;
                        break;
                    case message_type_event_scan:
                        $Message->eventKey = $msg->eventKey;
                        $Message->ticket = $msg->ticket;
                        break;
                    case message_type_event_location:
                        $Message->locationX = $msg->latitude;
                        $Message->locationY = $msg->longitude;
                        $Message->scale = $msg->precision;
                        break;
                    default:
                        $Message->event = (String)$msg->event;
                        $Message->eventKey = (String)$msg->eventKey;
                        break;
                }
                break;
            }
            case message_type_image:
                $Message->picUrl = trim($msg->picUrl);
                break;
            case message_type_voice:
                /*MediaId	语音消息媒体id，可以调用多媒体文件下载接口拉取数据。
                Format	语音格式，如amr，speex等
                MsgID	消息id，64位整型*/
                $Message->mediaId = trim($msg->mediaId);
                $Message->format = trim($msg->format);
                break;
            case message_type_video:
                /*MediaId	视频消息媒体id，可以调用多媒体文件下载接口拉取数据。
                ThumbMediaId	视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据。
                MsgId	消息id，64位整型*/
                $Message->mediaId = trim($msg->mediaId);
                $Message->thumbMediaId = trim($msg->thumbMediaId);
                break;
            case message_type_location:
                $Message->locationX = $msg->locationX;
                $Message->locationY = $msg->locationY;
                $Message->scale = $msg->scale;
                $Message->label = $msg->label;
                break;
            case message_type_link:
                $Message->title = trim($msg->title);
                $Message->description = trim($msg->description);
                $Message->url = trim($msg->url);
                break;
            default:
                // 记录日志
        }

        $result = $Message->add();
        if (!$result) {
            Log::write('Add Message Error:' . $Message->getError());
        }
    }

    /**
     * 重置用户状态
     *
     * @param $message
     * @return null
     */
    private function resetUserStatus($message)
    {
        // 查询状态，如果onReady != YES，则使用对应插件处理
        $user = UserStatus::get($message->fromUserName);
        if (!isset($user) || $user->onReady == 1)
            return NULL;

        $userStatus = UserStatus::create($message->fromUserName, 0);
        $userStatus->status = '0';
        $userStatus->reserve1 = NULL;
        $userStatus->reserve2 = NULL;
        $userStatus->reserve3 = NULL;
        $userStatus->reserve4 = NULL;
        $userStatus->reserve5 = NULL;
        UserStatus::end($userStatus);
    }

    /**
     * 处理用户状态
     *
     * @param $message
     * @return mixed|null
     */
    private function handleUserStatus($message)
    {
        Log::write('Enter function handleUserStatus');

        // 查询状态，如果onReady != YES，则使用对应插件处理
        $user = UserStatus::get($message->fromUserName);
        if (!isset($user) || $user->onReady == 1)
            return NULL;

        $materialModel = D('material');
        $material = (object)$materialModel->getById($user->materialId);
        return Module::doModule($material->module, $message, $material, $user);
    }

    /**
     * 文本默认回复
     * default_reply
     *
     * @param $message
     * @return mixed
     */
    private function handleDefault($message)
    {
        Log::write('Enter function responseDefault');

        //默认回复使用输入提示
        $params = new stdClass();
        $params->keyword = keyword_default_reply;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    /**
     * 处理文本消息
     *
     * @param $message
     * @return mixed
     */
    private function handleText($message)
    {
        Log::write('Enter function handleText');
        $this->handleUserInfo($message, module_handle_text);
        $status = new stdClass();
        $status->status = 0;
        // 关键字查询
        $messageResult = Module::doModule("messageSearch", $message, NULL, $status);
        // 返回$messageResult, 看messageSearchModule里sendBySerialNumber方法
        // 如果有返回, 说明查询的关键字对应的素材没有上传到微信素材库, 为了避免被动消息查询5秒超时轮询, 这里采用再次异步请求的方式
        if ($messageResult) {
            if ($messageResult->ispost) {
                $this->postCallModule($messageResult);      // 调用异步
            }
            return $messageResult;
        }
        // 关键字轮询
        return Module::doModule('keyword', $message, NULL, NULL);
    }

    /**
     * 处理user表中消息相关用户信息,判断存在以及更新
     *
     * @param $message
     * @param $pointType
     */
    private function handleUserInfo($message, $pointType)
    {
        Log::write('Enter function handleUserInfo');
        // 确定当前客户
        $customer = $this->currentCustomer();
        //
        $userModel = D('user');
        $where['openid'] = $message->fromUserName;

        $user = $userModel->where($where)->find();
        Log::write(json_encode($message));
        if (isset($user)) {
            $userModel->lastTime = $message->createTime;
            //$userModel->status = 'subscribe';
            $userModel->where($where)->save();
        } else {
            $userModel->create();
            $userModel->userName = $message->fromUserName;
            $userModel->openid = $message->fromUserName;
            // TODO: 这里需要改表结构
//            $userModel->mediaId = $customer->id;
            $userModel->customerId = $customer->cid;
            $userModel->profileUrl = DEFAULT_PROFILE_URL;
            $userModel->lastTime = $message->createTime;
            $userModel->status = USER_STATUS_SHARE_SUBSCRIBE;
            $result = $userModel->add();
            if (!$result) {
                Log::write('handleUserInfo error:' . $userModel->getLastSql());
            }

            $this->setUserInfo($message);
        }
        if (isset($pointType)) {
            set_point_by_point_type($pointType, $message->fromUserName, false);
        }
    }


    /**
     * 处理关注事件消息
     *
     * @param $message
     * @param $customer
     * @return mixed
     */
    private function handleSubscribe($message, $customer)
    {
        Log::write('Enter function handleSubscribe');

        // 确定当前客户
        $customer = $this->currentCustomer();
        // todo: 注意, 用到currentCustomer都得改一下
//        $customerId = $customer->id;
        $mediaId = $customer->id;
        $customerId = $customer->cid;

        /**
         * 这里只是用于查询设置自动分组情况
         * LLyeap_wx_customer修改
         */
        /***** LLyeap_delete *****/
//        $customerModel = M('customer');
        /*****  *****/

        Session::switchCustomer(0);
        $IndMediaInfo_Model = D('ind_media_info');
        $miMallUserModel = M("mimall_user");
        Session::switchCustomer($customerId);
        $userModel = D('user');

        $where['openid'] = $message->fromUserName;
        $user = $userModel->where($where)->find();
        if (isset($user)) {
            $redis = new RedisAPI();
            $redis->del('cid'.$customerId.'userId'.$user['id'].'userInfo');
            if ($message->eventKey) {
                $userModel->status = 'scansubscribe';
            } else {
                $userModel->status = 'subscribe';
            }
            $userModel->mediaId = $mediaId;
            $userModel->lastTime = $message->createTime;
            if ($user["status"] == "sharesubscribe") {
                $userModel->subscribeTime = date("Y-m-d H:i:s");
            }
            $userModel->where($where)->save();
        } else {
            $userModel->create();
            $userModel->userName = $message->fromUserName;
            $userModel->openid = $message->fromUserName;
            $userModel->customerId = $customer->id;
            $userModel->status = 'subscribe';
            $userModel->subscribeTime = date("Y-m-d H:i:s");
            if ($message->eventKey) {
                $userModel->status = 'scansubscribe';
            }
            $userModel->profileUrl = DEFAULT_PROFILE_URL;
            $userModel->lastTime = $message->createTime;
            $userModel->subscribeTime = $message->createTime;
            $userModel->mediaId = $mediaId;

            $userId = $userModel->add();
            $data['uId'] = $userId;
            R('call/newUserPoint', [$data]);//新用户积分
        }
        $this->setUserInfo($message);
        $paramsQRCode = new stdClass();
        $paramsQRCode->message = $message;
        $result = Module::callModule('qrcode', NULL, 'scanFromSubscribe', $paramsQRCode);

        $userName = $message->fromUserName;
        /*组织调用关注积分方法参数*/
        $data = $miMallUserModel->where(['openid' => $userName])->find();
        if (!$data) $data['uId'] = $userModel->where(['userName' => $userName])->getField('id');
        $data['mediaId'] = $mediaId;
        /***** LLyeap_delete *****/
//        $customerUserInfo = $customerModel->where('id=' . $customerId)->find();
        /*****  *****/

        $customerUserInfo = $IndMediaInfo_Model->where(['id' => $mediaId, 'cid' => $customerId])->find();

        // 判断自动写入分组信息
        if ($customerUserInfo['isAutoGroup']) {
            $userInfo = $userModel->where("userName='" . $userName . "'")->find();
            $groupId = $userInfo['groupId'];
            $groupid = explode(",", $groupId);
            $openids = explode(',', $userName);
            $moveResult = WeixinApi::setUsersTag($openids, end($groupid));
            $moveResult = json_decode($moveResult, true);
            if ($moveResult['errcode']) {
                Log::write("写入用户分组失败   " . $moveResult['errmsg']);
            }
            if (count($groupid) > 1) {
                $userModel->where("userName='" . $userName . "'")->setField("groupId", end($groupid));
            }
        }

        $this->subscribePoint($data); //关注积分
        /** 返回 */
        if ($result) {
            return $result;
        } else {
            $params = new stdClass();
            $params->keyword = keyword_system_subscribe;
            $params->message = $message;
            return Module::callModule('keyword', NULL, 'action', $params);
        }
    }

    private function subscribePoint($data)
    {
        $InviteRewardModel = D('InviteReward', 'Logic');
        $pointModel = D('Point', 'Logic');
        $points = $InviteRewardModel->getInvitePoint();
        foreach ($points as $point) {
            $pointConfig = [
                'userId' => $data['uId'],
                'miUid' => $data['miUid'],
                'refereeUid' => $data['refereeUid'],
                'preRefereeUid' => $data['preRefereeUid'],
                'recommenderId' => $data['recommenderId'],
                'subscribeUserPoint' => $point['subscribeUserPoint'],
                'subscribeMiPoint' => $point['subscribeMiPoint'],
                'subscribePreMiPoint' => $point['subscribePreMiPoint'],
                'subscribePrePreMiPoint' => $point['subscribePrePreMiPoint'],
                'subscribeRecommenderPoint' => $point['subscribeRecommenderPoint'],
                'pointSchemeId' => $point['pointSchemeId'],
                'pointSchemeName' => $point['pointSchemeName']
            ];
            if (!$point['noInviteSubscribeReward'] && !$pointConfig['recommenderId']) $pointConfig['subscribeUserPoint'] = 0;//非邀请情况不得积分
            if ($pointConfig['miUid'] == $pointConfig['userId']) $pointConfig['subscribeMiPoint'] = 0; //注册好友的注册好友是自己，不重复得积分

            $recordId = $InviteRewardModel->addInviteRecord(
                $data['uId'],
                $point['inviteRewardId'],
                $data['recommenderId'],
                1,
                null,
                1,
                $point['subscribeUserPoint'],
                0,
                null,
                json_encode($pointConfig),
                'subscribe',
                $data['mediaId']
            );

            if (!empty($pointConfig['subscribeUserPoint'])) { //给新用户加积分
                $pointModel->addPoint(
                    $pointConfig['userId'],
                    $pointConfig['subscribeUserPoint'],
                    'subscribe',
                    $recordId,
                    '关注公众号',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribeMiPoint']) && $pointConfig['miUid']) { //给注册好友积分
                $pointModel->addPoint(
                    $pointConfig['miUid'],
                    $pointConfig['subscribeMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友关注公众号',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribePreMiPoint']) && $pointConfig['refereeUid']) { //给注册好友推荐人积分
                $pointModel->addPoint(
                    $pointConfig['refereeUid'],
                    $pointConfig['subscribePreMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友关注公众号',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribePrePreMiPoint']) && $pointConfig['preRefereeUid']) { //给注册好友上级推荐人积分
                $pointModel->addPoint(
                    $pointConfig['preRefereeUid'],
                    $pointConfig['subscribePrePreMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友关注公众号',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribeRecommenderPoint']) && $pointConfig['recommenderId']) { //给推荐好友积分
                $pointModel->addPoint(
                    $pointConfig['recommenderId'],
                    $pointConfig['subscribeRecommenderPoint'],
                    'subscribe',
                    $recordId,
                    '好友关注公众号',
                    '',
                    $point['pointSchemeId'],
                    $point['pointSchemeName']
                );
            }
        }
    }

    /**
     * 处理取消关注事件消息
     *
     * @param $message
     * @return mixed
     */
    private function handleUnsubscribe($message)
    {
        Log::write('Enter function handleUnsubscribe');
        // 确定当前客户
        $customer = $this->currentCustomer();
        $mediaId = $customer->id;
        $customerId = $customer->cid;
        //
        $userModel = D('user');
        $where['openid'] = $message->fromUserName;

        $user = $userModel->where($where)->find();
        if (isset($user)) {
            $redis = new RedisAPI();
            $redis->del('cid'.$customerId.'userId'.$user['id'].'userInfo');

            $userModel->status = 'unsubscribe';
            $userModel->unsubscribeTime = $message->createTime;
            $userModel->lastTime = $message->createTime;
            $userModel->mediaId = $mediaId;
            $userModel->where($where)->save();
        } else {
            $userModel->create();
            $userModel->userName = $message->fromUserName;
            $userModel->openid = $message->fromUserName;
            // TODO: 这里需要修改表结构
//            $userModel->mediaId = $customer->id;
            $userModel->customerId = $customer->cid;
            $userModel->profileUrl = DEFAULT_PROFILE_URL;
            $userModel->lastTime = $message->createTime;
            $userModel->status = 'unsubscribe';
            $userModel->unsubscribeTime = $message->createTime;
            $userModel->subscribeTime = NULL;
            $userModel->mediaId = $mediaId;
            $userId = $userModel->add();
            $data['uId'] = $userId;
            R('call/newUserPoint', [$data]);//新用户积分
        }
        Session::switchCustomer($customerId);
        $this->deductSubscribePoint($user['id'], $mediaId);
        //
//     	$userModel = D('user');
//     	$where['userName'] = $message->fromUserName;

//     	$userModel->status = 'unsubscribe';
//     	$userModel->unsubscribeTime = $message->createTime;
//     	$userModel->lastTime = $message->createTime;
//     	$userModel->where($where)->save();

        //
        $params = new stdClass();
        $params->keyword = keyword_system_unsubscribe;
        $params->message = $message;
        //自由购取消关注处理
        Module::callModule('freebuy', NULL, 'removeOrderRefue', $params);
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    private function deductSubscribePoint($userId, $mediaId)
    {
        $customerId = Session::$user['customerId'];
        $inviteRewardModel = D('InviteReward', 'Logic');
        $pointModel = D('Point', 'Logic');

        $where = [
            'userId' => $userId,
            'type' => 1,
            'cid' => $customerId,
            'moduleId' => $mediaId,
            'deducted' => 0
        ];
        $inviteRecords = $inviteRewardModel->getInviteRecord($where);

        foreach ($inviteRecords as $inviteRecord) {
            $recordId = $inviteRecord['id'];
            $pointConfig = json_decode($inviteRecord['pointConfig'], true);

            if (!empty($pointConfig['subscribeUserPoint'])) { //扣除取关者积分
                $pointModel->deductPoint(
                    $pointConfig['userId'],
                    $pointConfig['subscribeUserPoint'],
                    'subscribe',
                    $recordId,
                    '取关公众号',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribeMiPoint']) && $pointConfig['miUid']) { //扣除注册好友积分
                $pointModel->deductPoint(
                    $pointConfig['miUid'],
                    $pointConfig['subscribeMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友取关公众号',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribePreMiPoint']) && $pointConfig['refereeUid']) { //扣除注册好友推荐人积分
                $pointModel->deductPoint(
                    $pointConfig['refereeUid'],
                    $pointConfig['subscribePreMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友取关公众号',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribePrePreMiPoint']) && $pointConfig['preRefereeUid']) { //扣除注册好友上级推荐人积分
                $pointModel->deductPoint(
                    $pointConfig['preRefereeUid'],
                    $pointConfig['subscribePrePreMiPoint'],
                    'subscribe',
                    $recordId,
                    '好友取关公众号',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['subscribeRecommenderPoint']) && $pointConfig['recommenderId']) { //扣除推荐好友积分
                $pointModel->deductPoint(
                    $pointConfig['recommenderId'],
                    $pointConfig['subscribeRecommenderPoint'],
                    'subscribe',
                    $recordId,
                    '好友取关公众号',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }
            $where = ['id' => $inviteRecord['id']];
            $data = ['deducted' => 1];
            $res = $inviteRewardModel->updateInviteRecord($where, $data);
        }
    }

    /**
     * 处理菜单点击事件消息
     *
     * @param $message
     * @return mixed|null
     */
    private function handleClick($message)
    {
        $this->handleUserInfo($message);

        $MenuModel = M('menu');
        $eventKey = $message->eventKey;
        $keyword = $MenuModel->where("eventKey='$eventKey'")->getField('keyword');
        if (!$keyword) {
            return NULL;
        }
        $params = new stdClass();
        $params->keyword = $keyword;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    /**
     * 处理菜单点击事件消息
     *
     * @param $message
     */
    private function handleView($message)
    {
        $this->handleUserInfo($message);

        // 不返回消息，避免点击菜单同时回复消息
        return;
    }

    /**
     * 处理扫码事件
     *
     * @param $message
     * @return mixed
     */
    private function handleScan($message)
    {
        Log::write("Enter function handleScan");
        $this->handleUserInfo($message, module_handle_qrcode);

        $params = new stdClass();
        $params->message = $message;
        return Module::callModule('qrcode', NULL, 'scanFromScan', $params);
    }

    /**
     * 事件推送群发结果处理
     *
     * @param $message
     */
    private function handleMass($message)
    {
        Log::write('Enter function handleMass');
        // 确定当前客户
        $customer = $this->currentCustomer();
        log::write("msgid=" . $message->msgid);
        log::write("msg=" . $message);
        //
        $Model = D('module_mass_havesend');
        $where['msg_id'] = $message->msgid;
//        $where['toUserName'] = $message->ToUserName;

        $havesend = $Model->where($where)->find();
        if (isset($havesend)) {
            $Model->toUserName = $message->ToUserName;
            $Model->fromUserName = $message->FromUserName;
            $Model->sentcount = $message->sentcount;
            $Model->errorcount = $message->errorcount;
            $Model->filtercount = $message->filtercount;
            $Model->totalcount = $message->totalcount;
            $Model->returnStatus = $message->status;
            $Model->returntime = date('Y-m-d H:i:s');;
            $result = $Model->where($where)->save();
            if (!$result) {
                Log::write("[Callback - handleMass error:]" . $Model->getLastSql());
            }
        } else {
            Log::write("[Callback - handleMass error not found msg:]" . $Model->getLastSql());
        }

        /*保存群发消息回调的状态*/
        Log::write('jie群发图文(第二次)回调返回的消息' . print_r($message, true));
        if ($message->newsStatus == 'send success') {
            $status = 'success';
        } else if ($message->newsStatus == 'send fail') {
            $status = 'fail';
        } else {
            $status = $message->newsStatus;
        }
        $sql = "UPDATE `wx_news_index_comment` SET `status`='" . $status . "' WHERE ( `wxappid` = '" . $message->toUserName . "' ) AND ( `msg_id` = " . $message->msgid . " )";
        $updateRet = M()->execute($sql);
        //Log::write('jie群发图文(第二次)各条索引状态保存失败:'.M()->getLastSql());
        if (!$updateRet) {
            Log::write('jie群发图文(第二次)各条索引状态保存失败:' . M()->getLastSql());
        }
    }

    /**
     * 缺省处理图片消息
     *
     * @param $message
     * @return mixed
     */
    private function handleImage($message)
    {
        Log::write('Enter function handleImage');
        $this->handleUserInfo($message, module_handle_image);

        $params = new stdClass();
        $params->keyword = keyword_default_image_reply;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    /**
     * 缺省处理位置消息
     *
     * @param $message
     * @return mixed
     */
    private function handleLocation($message)
    {
        Log::write('Enter function handleLocation');
        $this->handleUserInfo($message, message_type_location);

        $params = new stdClass();
        //$params->keyword = keyword_default_location_reply;
        $params->message = $message;
        return Module::callModule('location', NULL, 'getNearlyStore', $params);
    }

    /**
     * 缺省处理链接消息
     *
     * @param $message
     * @return mixed
     */
    private function handleLink($message)
    {
        Log::write('Enter function handleLink');
        $this->handleUserInfo($message);

        $params = new stdClass();
        $params->keyword = keyword_default_link_reply;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    /**
     * 缺省处理语音消息
     *
     * @param $message
     * @return mixed
     */
    private function handleVoice($message)
    {
        Log::write('Enter function handleVoice');
        $this->handleUserInfo($message, module_handle_voice);


        $params = new stdClass();
        $params->keyword = KEYWORD_DEFAULT_AUDIO_REPLY;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    /**
     * 缺省处理视频消息
     *
     * @param $message
     * @return mixed
     */
    private function handleVideo($message)
    {
        Log::write('Enter function handleVideo');
        $this->handleUserInfo($message, module_handle_video);

        $params = new stdClass();
        $params->keyword = KEYWORD_DEFAULT_VIDEO_REPLY;
        $params->message = $message;
        return Module::callModule('keyword', NULL, 'action', $params);
    }

    private function handleService($message)
    {
        Log::write('Enter function transferCustomerService');
        return Module::doModule('transferCustomerService', $message, NULL, NULL);
    }


    private function setUserInfo($message)
    {
//        \Log::write(json_encode($message));
        $openid = $message->fromUserName;
        $result = WeixinApi::getUserInfo($openid);
//        Log::write("获取关注人信息" . json_encode($result));
        if (!isset($result)) {
            return;
        }
        $unionid = $result->unionid;
        $UserWeixinInfoModel = D('user_weixin_info');
        $UserModel = D('user');
        $condition['openid'] = $message->fromUserName;
        $userId = $UserModel->where($condition)->getField("id");
        if ($unionid) {
            $where['unionid'] = $unionid;
            $userInfo = $UserWeixinInfoModel->where($where)->find();
            if (!$userInfo) {
                $where = null;
                $where['openid'] = $openid;
                $userInfo = $UserWeixinInfoModel->where($where)->find();
            }
        } else {
            $where['openid'] = $openid;
            $userInfo = $UserWeixinInfoModel->where($where)->find();
        }
        $subscribe_time = date("Y-m-d H:i:s");
        if (isset($userInfo)) {
            $UserWeixinInfoModel->subscribe = $result->subscribe;
            $UserWeixinInfoModel->nickname = $result->nickname;
            $UserWeixinInfoModel->sex = $result->sex;
            $UserWeixinInfoModel->language = $result->language;
            $UserWeixinInfoModel->city = $result->city;
            $UserWeixinInfoModel->province = $result->province;
            $UserWeixinInfoModel->country = $result->country;
            $UserWeixinInfoModel->headimgurl = $result->headimgurl;
            $UserWeixinInfoModel->subscribe_time = $subscribe_time;
            $UserWeixinInfoModel->unionid = $result->unionid;
            $UserWeixinInfoModel->userId = $userId;
            $UserWeixinInfoModel->where($where)->save();
        } else {
            $UserWeixinInfoModel->create();

            $UserWeixinInfoModel->openid = $openid;
            $UserWeixinInfoModel->subscribe = $result->subscribe;
            $UserWeixinInfoModel->nickname = $result->nickname;
            $UserWeixinInfoModel->sex = $result->sex;
            $UserWeixinInfoModel->language = $result->language;
            $UserWeixinInfoModel->city = $result->city;
            $UserWeixinInfoModel->province = $result->province;
            $UserWeixinInfoModel->country = $result->country;
            $UserWeixinInfoModel->headimgurl = $result->headimgurl;
            $UserWeixinInfoModel->subscribe_time = $subscribe_time;
            $UserWeixinInfoModel->unionid = $result->unionid;
            $UserWeixinInfoModel->userId = $userId;
            $UserWeixinInfoModel->add();
            Log::write("插入weixininfo表信息" . $UserWeixinInfoModel->getLastSql());
        }
        $customerId = Session::$user["customerId"];
        if($userId&&$customerId){
            $sql = "update wx_quan_user a inner join wx_miyouquan b on a.qid=b.id set a.nickName = '". $result->nickname."',a.headImgUrl='".$result->headimgurl."' where b.cId=$customerId and a.uid=$userId";
            M("")->query($sql);
        }
    }

}
